<?php

namespace Getonlyimg\CronBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class CronController extends Controller
{
    /**
     * @Route("/cron/index/")
     * @Template()
     */
    public function indexAction()
    {

        $url      = "http://esquire.ru/photo/the-black-sea";
        $url      = "http://esquire.ru/photo/gunkanjima";
        $url      = "http://esquire.ru/photo/foc";
        $url      = "http://esquire.ru/photo/cunningham";


//        $url      = "http://kaddr.com/2013/05/profifoto-e21-svobodnaya-tema-pobeditelyu-karta-pamyati-transcend-sd-32gb-uhs-i-300x/";
//        $url      = "http://kaddr.com/2013/05/profifoto-e20-morskaya-tema-pobeditelyu-karta-pamyati-transcend-sd-32gb-uhs-i-300x/";
//        $url      = "http://kaddr.com/2013/04/profifoto-e17-makro-pobeditelyu-karta-pamyati-transcend-sd-32gb-uhs-i-300x/";


        $page  = $this->getPage($url);
        $html     = $page['content'];

        set_time_limit(0);
        $time_start = microtime( true );

        $tidyContent = $this->cleanRepair($html);

        $dom = new \DOMDocument();
        $dom->loadXML($tidyContent);

        $xpath = new \DOMXPath($dom);

        // xpath будет немнгого отлечаться от того что можно сгенерить в браузере
        // так как полученая страница отличаеться от той что в браузере
        $content = $xpath->query("//div[@id='nfcontent']//div[@id='nfmaincont']//div[@class='content_full']//div[contains(@class , 'gallery')]/div[contains(@class , 'gallery_thumbnails')]/div[contains(@class , 'image-block')]/*/a");

        $x = array();
        foreach( $content as $a) {
            /** @var $a \DOMElement */

            $a->childNodes-
            $c = $a->getElementsByTagName("img");
            if ($c) {
                $x[] = $a->getAttribute('href');
            }
        }

//        $content2 = $xpath->query("//div[@id='main']/*/div[contains(@class, 'post-content')]//img[contains(@class, 'size-full')]");
//
//        $x2 = [];
//        foreach( $content2 as $img) {
//            /** @var $img \DOMElement */
//                $x2[] = $img->getAttribute('src');
//        }


        $totalTime = microtime( true ) - $time_start;

        return array(
            'x'=>$x ,
            //'x2'=>$x2 ,
            'time' => $totalTime
        );
    }

   /**
     * @Route("/cron/best/")
     * @Template()
     */
    public function bestAction()
    {

      $urls =  array(
'http://www.bestskinsever.com/apple-screen-protector-1/iphone-skin?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/apple-screen-protector-1/ipad-skins?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/apple-screen-protector-1/ipod?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/apple-screen-protector-1/macbook-skin?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/apple-screen-protector-1/other?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/android-products/google?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/android-products/htc-products?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/android-products/lg?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/android-products/motorola-products?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/android-products/tmobile-products?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/android-products/samsung?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/android-products/sony?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/cell-phones/blackberrys?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/cell-phones/smart-phones?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/apple-ipad?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/acer?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/amazon?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/archos?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/asus?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/barnes-noble?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/blackberry?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/fujitsu?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/google?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/hp?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/htc-1?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/motorola?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/samsung?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/toshiba?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/velocity-micro?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/tablets/viewsonic?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/portable-gaming/nintendo?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/portable-gaming/sony?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/media-players/apple?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/media-players/cowon?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/media-players/creative?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/media-players/iriver?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/media-players/microsoft?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/media-players/sandisk?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/media-players/toshiba?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/e-reader?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/laptops?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/auto-interior?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/cameras?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/diy-skins-1?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/gps-devices?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/headphones?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/lionel?dir=asc&limit=25&order=name',
'http://www.bestskinsever.com/other-stuff/watches?dir=asc&limit=25&order=name'
      );






        $serch = array(
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=1&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=2&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=3&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=4&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=5&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=6&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=7&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=8&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=9&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=10&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=11&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=12&q=Skin',
          'http://www.bestskinsever.com/catalogsearch/result/index/?limit=25&p=13&q=Skin',
        );



        foreach ($serch as $url) {
            $this->parse($url);
//           $res = $this->parse($url);
//            if (!empty($res)) {
//                foreach ($res as $page) {
//                    $this->parse($page);
//                }
//            }
        }

        ksort($this->result);
            // store an attribute for reuse during a later user request






        return array(
            'result' => $this->result,
            'count'=> count($this->result)
        );
    }

    public  $result = array();

    function parse($url) {


    $session = $this->getRequest()->getSession();

        //$session->set($url, false);

        if (!$session->get($url)) {

            $page  = $this->getPage($url);
            $html     = $page['content'];

            $session->set($url, $html);

        } else {
             $html = $session->get($url);
        }

        $tidyContent = $this->cleanRepair($html);
        $dom = new \DOMDocument();
        $dom->loadXML($tidyContent);
        $xpath = new \DOMXPath($dom);

        //$url = preg_split('/\?/', $url);

        //$title = $xpath->query("//a[@href='$url[0]']/span");

//        $groupName = $title->item(0)->nodeValue;
//
//        if (!array_key_exists($groupName, $this->result)) {
//            $this->result[$groupName] = '<b>' . $groupName . "</b><br>";
//        }

        $content = $xpath->query("//ol[@id='products-list']/li");





        if ($content->length) {

            foreach( $content as $li) {
                /** @var $li \DOMElement */

                $a = $xpath->query($li->getNodePath()."//h3/a");
                $skuNmae = $a->item(0)->nodeValue;
                $price = $xpath->query($li->getNodePath()."//p[@class='minimal-price']/span[2]");

                if ($price->length > 0) {
                     $label = 'Передняя панель: ';
                     $skuMinPrice = substr($price->item(0)->nodeValue,1);
                     $skuMinPriceTotal = floatval($skuMinPrice) + (floatval($skuMinPrice) / 2) + 3;

                } else {
                         $label = 'Весь набор (передняя, задняя, боковые панели): ';
                    $price = $xpath->query($li->getNodePath()."//div[@class='price-box']/span/span");

                    if ($price->length > 0) {
                        $skuMinPrice = substr($price->item(0)->nodeValue,1);
                        $skuMinPriceTotal = floatval($skuMinPrice) + (floatval($skuMinPrice) / 2) + 3;
                    }
                }

                $matches = preg_split('/Skin/', $skuNmae);

//                if (ceil($skuMinPriceTotal) - round($skuMinPriceTotal, 2) <= 0.5) {
//                    if (ceil($skuMinPriceTotal) - round($skuMinPriceTotal, 2) != 0.99) {
//                        $skuMinPriceTotal = floor($skuMinPriceTotal) + 0.99;
//                    }
//                } else {
//                    if (ceil($skuMinPriceTotal) - round($skuMinPriceTotal, 2) != 0.49) {
//                        $skuMinPriceTotal = floor(round($skuMinPriceTotal, 2)) + 0.49;
//                    }
//                }

                if (!empty($matches)) {
                    $this->result[trim($matches[0])] = " - <b>$label". "$". round($skuMinPriceTotal, 2) ."</b><br>";
                }
            }
        }




//            $pages = $xpath->query("//div[@class='pages']/ol/li/a");
//
//
//            $url2 = [];
//            if ($pages->length > 2) {
//
//                for ($i = 0; $i < $pages->length/2-1; $i++ ) {
//                    $url2[] = $pages->item($i)->getAttribute('href');
//                }
//
//            }

//        return $url2;


}

    /**
     * Получает информацию и странице по ссылке.
     * Корректно отработает даже если это не прямая ссылка на изображение.
     *
     * @param $url Ссылка на изображение
     *
     * @return array Ассоциативный массив с ключами "content" и "url"
     */
    private function getPage($url)
    {
        $options = array(
            CURLOPT_RETURNTRANSFER => true, // return web page
            CURLOPT_HEADER         => false, // do not return headers
            CURLOPT_FOLLOWLOCATION => true, // follow redirects
            CURLOPT_USERAGENT      => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31", // who am i
            CURLOPT_AUTOREFERER    => true, // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
            CURLOPT_TIMEOUT        => 120, // timeout on response
            CURLOPT_MAXREDIRS      => 10, // stop after 10 redirects
        );

        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        $content = curl_exec($ch);
        $header  = curl_getinfo($ch);
        curl_close($ch);

        $res            = array();
        $res['content'] = $content;
        $res['url']     = $header['url'];

        return $res;
    }

    private function cleanRepair($html)
    {
        $tidy = new \tidy();

        $tidy->parseString(
            $html,
            array(
                'output-xml'       => true,
                'clean'            => true,
                'numeric-entities' => true,
                'merge-divs' => false,
                'merge-spans' => false,
            ),
            'utf8'
        );

         $tidy->cleanRepair();

        return tidy_get_output($tidy);
    }

}
